<template>
  <su-page>
    <su-body padding="0 15px">
      <u--form labelPosition="top" :model="formData" :rules="rules" ref="form1">
        
        <u-form-item labelWidth="100px" label="企业名称" prop="title" borderBottom ref="item1">
          <u--input v-model="formData.title" placeholder="请输入企业名称" border="none"></u--input>
        </u-form-item>
		<u-form-item labelWidth="100px" label="项目经理" prop="spr" borderBottom ref="item1">
		 <!-- <su-select :options="sprOptions" placeholder="请选择项目经理" v-model="formData.spr"></su-select> -->
		   <u--input v-model="formData.spr" placeholder="请选择项目经理" border="none"></u--input>
		</u-form-item>
		<u-form-item labelWidth="100px" label="联系方式" prop="lxfs" borderBottom ref="item1">
		 <!-- <su-select :options="sprOptions" placeholder="请选择项目经理" v-model="formData.spr"></su-select> -->
		   <u--input v-model="formData.lxfs" placeholder="联系方式" border="none"></u--input>
		</u-form-item>
        <u-form-item labelWidth="100px" label="项目名称" prop="xmmc" borderBottom ref="item1">
          <su-select :options="sprOptions" placeholder="请选择项目" v-model="formData.xmmc" @change="bianhua(sprOptions)"></su-select>
        </u-form-item>
        <u-form-item labelWidth="100px" label="项目地址" prop="addr" borderBottom ref="item1">
          <u--input v-model="formData.addr" placeholder="请输入项目地址" border="none"></u--input>
        </u-form-item>
		
        <u-form-item labelWidth="100px" label="现场照片" prop="files" borderBottom ref="item1">
         <u-upload
         	:fileList="formData.files"
         	@afterRead="afterRead"
         	@delete="deletePic"
         	name="3"
         	multiple
         	:maxCount="10"
         	:previewFullImage="true"
         ></u-upload>
        </u-form-item>
      </u--form>
      <su-fixed-footer transparent>
        <u-button type="default" size="large" :loading="loading" text="取消" @click="goBack"></u-button>
        <u-button type="primary" size="large" :loading="loading" text="签到" @click="getLocation"></u-button>
      </su-fixed-footer>
    </su-body>
  </su-page>
</template>

<script>
  /**
   * @description 发起流程
   * @date 2022-03-15
   * @version v1.0.1
   * @author gf
   */
  import {
    register
  } from '@/common/api.js'
    import {runSQL} from '@/common/utils/wxutils.js'

import config from '../../../../uni_modules/uview-ui/libs/config/config';
 let long='';
 let lat='';
 let gcxzb='';
 let gcyzb='';
 let rid;
  export default {
    data() {
      return {
        loading: false,
        sprOptions: [],
        // form表单数据对象	
        formData: {
          title: '',
          spr: '',
		  recid:null,
		  gcbh:'',
		  xzb:'',
		  yzb:'',
		   spr: '',
		  lxfs: '',
          yjjy: '',
		  long:'',
		  lat:'',
		  longlat:'',
          jindu:'',
          files:[],
		  fjid:[],
		  xmmc:'',
		  humanid:'',
        },
		
        // 表单校验规则
        rules: {
          title: [{
            required: true,
            message: '请填写企业名称',
            trigger: ['change', 'blur'],
          }],
          yjjy: [{
            required: true,
            message: '请填写意见建议',
            trigger: ['change', 'blur'],
          }],
          spr: {
            required: true,
            validator: (rule, value, callback) => {
              return value !== '';
            },
            message: '请选择项目经理',
            trigger: ['change'],
          },
        }
      }
    },
    onLoad() {
      this.$nextTick(()=>{
        this.$refs.form1.setRules(this.rules)
      })
	   let list=[];
	    runSQL("select * from ssnydw.tbhuman where humanid="+this.$store.state.token+";").then(res=>{
			this.formData.spr=res[0][0].HUMANNAME;
			this.formData.title=res[0][0].UNITNAME;
			this.formData.lxfs=res[0][0].CELLPHONE;
			this.formData.humanid=res[0][0].HUMANID;
			runSQL("select * from ssnydw.gcbdxxb where zcbqymc='"+res[0][0].UNITNAME+"' and ZCBXMFZR='"+res[0][0].HUMANNAME+"' and gczt='在建';").then(ress=>{
				 for(let i=0;i<ress[0].length;i++){
					 list.push({
						label: ress[0][i].GCMC,
						value: ress[0][i].RECID,
						xmdz: ress[0][i].GCDZ,
						gcbh: ress[0][i].GCBH,
						xzb: ress[0][i].X,
						yzb: ress[0][i].Y,
					 })
					 }
				})
			})
				this.sprOptions=list	
    },
    methods: {
		async afterRead(event) {
			let lists = [].concat(event.file)
			let fileListLen = this.formData.files.length
			lists.map((item) => {
				this.formData.files.push({
					...item,
					status: 'uploading',
					message: '上传中'
				})
			})
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url);
				// this.insertImg(result);
				let item = this.formData.files[fileListLen]
				this.formData.files.splice(fileListLen, 1, Object.assign(item, {
					status: 'success',
					message: '',
					data:JSON.parse(result.data) 
					// url: result
				}))
				fileListLen++
			}
		},
		uploadFilePromise(url) {
			console.log("aaaaaaaaaaa",rid)
		
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: 'http://120.221.95.208:8083/HdzjAppport/uploadb', // 仅为示例，非真实的接口地址`${zhhfurl}zhhf-info/WeChat/getOpenId`,
					filePath: url,
					name: 'file',
					formData: {
						recid: rid
					},
					success: (res) => {
						let obj = JSON.parse(res.data)
							let oo = JSON.stringify(obj)
						setTimeout(() => {
							this.formData.fjid.push(
								obj.fileid
							)
							
							resolve(res);
						}, 1000)
					},
						fail(err) {
							console.log(err)
						}
				});
			})
		},
		deletePic(event) {
			this.formData.files.splice(event.index, 1)
			this.formData.fjid.splice(event.index, 1)
		},
      goBack(){
        this.$u.route({
          type:'back'
        })
      },
	  bianhua: function (e) {
		 
		  this.formData.addr=e[0].xmdz;
		  this.formData.recid=e[0].value;
		  this.formData.gcbh=e[0].gcbh;
		  this.formData.xzb=e[0].xzb;
		  this.formData.yzb=e[0].yzb;
		  this.formData.xmmc=e[0].label;
		  gcxzb=e[0].xzb.toFixed(6);
		  gcyzb=e[0].yzb.toFixed(6);
		  rid=e[0].value;
		  
	  },
    
	 
			getLocation(){
				let data=this.formData;
			    let vta=this.$u;
						return new Promise((reserve, reject) => { //因为获取位置是异步接口所以需要使用promise
							uni.getLocation({
								success(res) {
									reserve(location);
									console.log("当前位置",res.longitude,res.latitude)
							runSQL("select ST_Distance(ST_GeomFromEWKT('SRID=4490;POINT("+gcxzb+" "+gcyzb+")')::geography,ST_SetSRID(ST_Point("+res.longitude+"::double precision, "+res.latitude+"::double precision), 4490)::geography)ldjl;").then(res=>{
								
								if(res[0][0].LDJL<1000){
									let xczp="";
									for(let i=0;i<data.fjid.length;i++){
									if(i==0){
									       xczp=data.fjid[i];
										}else{
										  xczp=xczp+","+data.fjid[i];
										}								
										}
									
										runSQL("select o_recid as recidn from fnstartworkflowsql(243364, "+data.humanid+");").then(resd=>{
											
						                runSQL("insert into WSQD(recid,QYMC,XMJL,LXFS,XMMC,XMDZ,XCZP,XMid,GCBH,QDRQ,QDNF,QDYF,humanid,qdday)values("+resd[0][0].RECIDN+",'"+data.title+"','"+data.spr+"','"+data.lxfs+"','"+data.xmmc+"','"+data.addr+"','"+xczp+"',"+rid+",'"+data.gcbh+"',now(),extract(year from now()),extract(month from now()),"+data.humanid+",extract(day from now()));").then(ress=>{
								if(ress[0]==1){
									if(data.files.length>0){
																										
										 for(let a=0;a<data.files.length;a++){
											let fhsj=data.files[a].data;
											let fjpn=fhsj.url.split("D://SSNYDWFile")[1];
											let fjpth=fjpn.split(fhsj.wjm)[0]; 
											console.log("aa",fjpth);
											runSQL("insert into tbfile (fileid,filename,filepath,filesize,lastupdate,humanid,storefilename,serverid,disporder,version)values('"+fhsj.fileid+"','"+fhsj.wjm+"','"+fjpth+"',1024,now(),"+data.humanid+",'"+fhsj.wjm+"',1,"+rid+",1);").then(resc=>{
																												
											})						 
											} 
											}
											
											
											uni.$u.toast('签到成功！');
											vta.route({
											type:'back'
											})
											
											
											
								}else{
									uni.$u.toast('签到失败！');
								}
								
								
								})
								})
								
								}else{
									uni.$u.toast('签到失败，请在项目一公里范围内签到！');
								}
								
								})
								},
								fail(err) {
									reject(location); //获取失败则返回经纬坐标为0
								}
							})
						})	
						
						},
			
	 
	
	  
	  
    }
  }
</script>

<style lang="scss">
</style>
